﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
using Mulala.Cavan.Domain.MainBoundedContext.DictionaryModule;
using Mulala.Cavan.Domain.MainBoundedContext.MulalaModule;
using Mulala.Cavan.Domain.MainBoundedContext.SearchModule;
using Mulala.Cavan.Domain.MainBoundedContext.CorporationModule;
using Mulala.Cavan.Core.Helper;
using Mulala.Cavan.Core.Extension;

namespace Mulala.Cavan.Application.MainBoundedContext.MulalaModule
{
    public static class TagConverter
    {
        public static string ConvertToTagText(this int id)
        {
            IApplicationContext context = ContextRegistry.GetContext();
            ITagAppService tagAppService = context.GetObject(MulalaAppServiceConst.TAGAPPSERVICE) as ITagAppService;

            Tag tag = tagAppService.GetById(id);

            if (null != tag)
            {
                return tag.Text;
            }
            return string.Empty;
        }

        public static string ConvertToTagText(this string value, DictionaryIdentifier.GroupType type)
        {
            IApplicationContext context = ContextRegistry.GetContext();
            ITagAppService tagAppService = context.GetObject(MulalaAppServiceConst.TAGAPPSERVICE) as ITagAppService;
            TagSearch tagSearch = TagSearchFactory.CreateTagSearch(type, value);

            Tag tag = tagAppService.GetSingleBySearch(tagSearch);

            if (null != tag)
            {
                return tag.Text;
            }
            return string.Empty;
        }

        public static string ConvertToTagText(this int[] values, DictionaryIdentifier.GroupType type)
        {
            IApplicationContext context = ContextRegistry.GetContext();
            ITagAppService tagAppService = context.GetObject(MulalaAppServiceConst.TAGAPPSERVICE) as ITagAppService;
            StringBuilder sbText = new StringBuilder();
            foreach (int value in values)
            {
                TagSearch tagSearch = TagSearchFactory.CreateTagSearch(type, value.ToString());
                Tag tag = tagAppService.GetSingleBySearch(tagSearch);

                if (null != tag)
                {
                    sbText.Append(tag.Text + ",");
                }
            }
            string result = string.Empty;
            if (sbText.ToString().IsNotEmpty())
            {
                result = StringHelper.ClearLastChar(sbText.ToString());
            }

            return result;
        }
    }
}
